let effectFn
function effect(fn) {
    effectFn = fn
    fn()
}

/**
 * 副作用函数中被读取的数据必须被代理
 */
function proxyData(data) {
    let bucket = new WeakMap()
    function track(target,key){
        if (!effectFn) return target[key]
            let depsMap = bucket.get(target)
            if (!depsMap) {
                bucket.set(target, depsMap = new Map())
            }
            let effects = depsMap.get(key)
            if (!effects) {
                depsMap.set(key, effects = new Set())
            }
            effects.add(effectFn)
    }

    function trigger(target,key){
        let depsMap = bucket.get(target)
            if (!depsMap) {
                return
            }
            const effets = depsMap.get(key)
            effets && effets.forEach(fn => fn())
    }
    return new Proxy(data, {
        get(target, key) {
            track(target,key)
            return target[key]
        },
        set(target, key, newVal) {
            target[key] = newVal
        }
    })
}


//test code
let obj = { text: "hello" }
obj = proxyData(obj)

// 副作用函数
function readObj() {
    console.log(obj.text)
}
// 执行副作用函数，触发读取
effect(readObj)
// 1 秒后修改响应式数据
setTimeout(() => {
    obj.text = 'hello vue3'
}, 1000)





